import ImageOrIcon from '@/components/ImageOrIcon';
import DefaultNavBar from '@/components/StandNavBar/DefaultNavBar';
import pNoCard from '@/giftCardSubPack/images/giftCardSelect/no-card.png';
import { debounce } from '@/utils/helper';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import utils from '@/utils/index';
import { Button, Image, Text, View } from '@tarojs/components';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import classNames from 'classnames';
import React, { useState } from 'react';
import { connect } from 'react-redux';
import pUnselected from '../images/giftCardSelect/cardUnselect.png';
import './index.scss';

const GiftCardSelect = ({ dispatch, loading, giftCardSelected }) => {
  useShowLoading(loading, ['giftCard/fineCardGetCardList']);

  const [isActiveTab, setIsActiveTab] = useState(true);
  const [validCardList, setValidCardList] = useState([]);
  const [invalidCardList, setInvalidCardList] = useState([]);
  const selectCardIds = giftCardSelected.map((v) => v.id);

  let urlParms = { isUnSelect: false };
  const router = useRouter();
  const { params = {} } = router;
  if (params.isUnSelect) {
    urlParms.isUnSelect = true;
  }

  const handleTabs = (active) => {
    setIsActiveTab(active);
  };

  const toggleSelectCard = (id) => {
    let ids = [];
    if (selectCardIds.includes(id)) {
      ids = selectCardIds.filter((v) => v !== id);
    } else {
      ids = [...selectCardIds, id];
    }
    dispatch({
      type: 'productCar/setGiftCardSelect',
      payload: validCardList.filter((v) => ids.includes(v.id)).slice(),
    });
  };

  const handleSave = debounce(() => {
    Taro.navigateBack({ url: '/orderSubPack/confirmOrder/index' });
  }, 2000);

  useDidShow(() => {
    dispatch({
      type: 'fineCard/fineCardGetCardList',
      payload: {
        status: 1,
        storeId: params.orgId,
      },
    }).then((res) => {
      setValidCardList(res.filter((v) => Object.keys(v).length > 0));
    });
    dispatch({
      type: 'fineCard/fineCardGetCardList',
      payload: {
        status: 2,
        storeId: params.orgId,
      },
    }).then((res) => {
      setInvalidCardList(res.filter((v) => Object.keys(v).length > 0));
    });
  }, []);

  return (
    <>
      <DefaultNavBar title="提货券" />
      <View className="gift-card-select">
        <View className="gift-card-select-tab customePageBackgroundStyle">
          <View
            className={classNames('item', {
              [`active customePageBorderStyle customePageStyle`]: isActiveTab,
            })}
            onClick={() => handleTabs(true)}
          >
            <View className="top">
              可用券（<Text className="desc">{validCardList.length}</Text>）
            </View>
          </View>

          <View
            className={classNames('item', {
              [`active customePageBorderStyle customePageStyle`]: !isActiveTab,
            })}
            onClick={() => handleTabs(false)}
          >
            <View className="top">
              不可用券（<Text className="desc">{invalidCardList.length}</Text>）
            </View>
          </View>
        </View>

        <View
          className="inner-wrap"
          style={{
            marginBottom: `${
              utils.getSizeByScale(116) + utils.getSizeByScale(49) + Taro.$bottomHight
            }px`,
          }}
        >
          <>
            {(isActiveTab ? validCardList : invalidCardList).map((card) => {
              const { balance, cardNum, id } = card;

              return (
                <View
                  className={classNames('giftcard')}
                  key={id}
                  onClick={() => {
                    !urlParms.isUnSelect && toggleSelectCard(id);
                  }}
                >
                  <View className="gtop">
                    <Text>券号：</Text>
                    <Text className="tnum">{cardNum.replace(/(.{4})/g, '$1 ')}</Text>
                  </View>
                  {isActiveTab ? (
                    <View className="gstatus">
                      {!urlParms.isUnSelect && (
                        <View className="icon-wrap">
                          <ImageOrIcon
                            {...{
                              className: 'icon',

                              name: selectCardIds.includes(id) && 'icon_chose',
                              size: 60,

                              src: pUnselected,
                            }}
                          />

                          <View className="placeholder"></View>
                        </View>
                      )}
                    </View>
                  ) : null}
                  <View className="gbottom">
                    <View className="tip">余额</View>
                    <View className="cnt">
                      <View className="left">
                        <Text className="unit">¥</Text>
                        <Text className="price">{balance}</Text>
                      </View>
                    </View>
                  </View>
                </View>
              );
            })}
            {((isActiveTab && !validCardList.length) ||
              (!isActiveTab && !invalidCardList.length)) && (
              <View className="empty-wrap">
                <Image className="empty" src={pNoCard}></Image>
                <View className="txt">无可用提货券</View>
              </View>
            )}

            <View
              className="bottom"
              style={{
                height: `${utils.getSizeByScale(116) + Taro.$bottomHight}px`,
              }}
            >
              <View className={urlParms.isUnSelect ? 'btn-single' : 'btn-two'}>
                <Button
                  className={classNames('btn customePageBorderStyle', {
                    'btn-yellow customePageBackgroundStyle': urlParms.isUnSelect,
                    customePageStyle: !urlParms.isUnSelect,
                    'btn-h5': process.env.TARO_ENV === 'h5',
                  })}
                  onClick={() =>
                    Taro.navigateTo({
                      url: '/giftCardSubPack/giftCardBind/index',
                    })
                  }
                >
                  绑定提货券
                </Button>
              </View>
              {!urlParms.isUnSelect && (
                <View className="btn-two btn-save">
                  <Button
                    className="btn btn-yellow customePageBackgroundStyle"
                    onClick={handleSave}
                  >
                    保存并使用
                  </Button>
                </View>
              )}
            </View>
          </>
        </View>
      </View>
    </>
  );
};
export default connect(({ loading, productCar }) => ({
  loading,
  giftCardSelected: productCar.giftCardSelected,
}))(GiftCardSelect);
